package gui;

import entity.Score;
import entity.Student;
import service.ScoreManager;
import service.StudentManager;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.util.Map;

/**
 * 成绩管理面板
 */
public class ScorePanel extends JPanel {
    private final ScoreManager scoreManager;
    private final StudentManager studentManager;
    
    // UI组件
    private JTable scoreTable;
    private DefaultTableModel tableModel;
    private JComboBox<String> studentComboBox;
    private JTextField chineseField, mathField, englishField;
    private JButton addButton, updateButton, deleteButton, clearButton;
    private JTextField searchField;
    private JButton searchButton, exportButton;
    
    /**
     * 构造函数
     */
    public ScorePanel(ScoreManager scoreManager, StudentManager studentManager) {
        this.scoreManager = scoreManager;
        this.studentManager = studentManager;
        initUI();
    }
    
    /**
     * 初始化UI
     */
    private void initUI() {
        setLayout(new BorderLayout(10, 10));
        setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        
        // 创建顶部搜索面板
        JPanel searchPanel = createSearchPanel();
        
        // 创建表格
        createTable();
        
        // 创建表单
        JPanel formPanel = createFormPanel();
        
        // 创建按钮面板
        JPanel buttonPanel = createButtonPanel();
        
        // 将表单和按钮面板放在一起
        JPanel inputPanel = new JPanel(new BorderLayout());
        inputPanel.add(formPanel, BorderLayout.CENTER);
        inputPanel.add(buttonPanel, BorderLayout.SOUTH);
        
        // 添加组件到面板
        add(searchPanel, BorderLayout.NORTH);
        add(new JScrollPane(scoreTable), BorderLayout.CENTER);
        add(inputPanel, BorderLayout.SOUTH);
        
        // 初始化表格数据
        refreshData();
    }
    
    /**
     * 创建搜索面板
     */
    private JPanel createSearchPanel() {
        JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        panel.setBorder(BorderFactory.createTitledBorder("搜索成绩"));
        
        searchField = new JTextField(20);
        searchButton = ThemeManager.createButton("搜索");
        exportButton = ThemeManager.createSuccessButton("导出");
        
        searchButton.addActionListener(e -> searchScores());
        exportButton.addActionListener(e -> exportScores());
        
        panel.add(new JLabel("搜索(学号/姓名):"));
        panel.add(searchField);
        panel.add(searchButton);
        panel.add(Box.createHorizontalStrut(20));
        panel.add(exportButton);
        
        return panel;
    }
    
    /**
     * 创建表格
     */
    private void createTable() {
        // 表格列名
        String[] columnNames = {"学号", "姓名", "语文", "数学", "英语", "总分"};
        
        // 创建表格模型
        tableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false; // 设置表格不可编辑
            }
        };
        
        // 创建表格
        scoreTable = new JTable(tableModel);
        scoreTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        scoreTable.getTableHeader().setReorderingAllowed(false);
        
        // 添加表格选择监听器
        scoreTable.getSelectionModel().addListSelectionListener(e -> {
            if (!e.getValueIsAdjusting()) {
                int selectedRow = scoreTable.getSelectedRow();
                if (selectedRow != -1) {
                    // 获取选中行的数据
                    String id = (String) tableModel.getValueAt(selectedRow, 0);
                    double chinese = (double) tableModel.getValueAt(selectedRow, 2);
                    double math = (double) tableModel.getValueAt(selectedRow, 3);
                    double english = (double) tableModel.getValueAt(selectedRow, 4);
                    
                    // 填充表单
                    studentComboBox.setSelectedItem(id);
                    chineseField.setText(String.valueOf(chinese));
                    mathField.setText(String.valueOf(math));
                    englishField.setText(String.valueOf(english));
                }
            }
        });
    }
    
    /**
     * 创建表单面板
     */
    private JPanel createFormPanel() {
        JPanel panel = new JPanel(new GridLayout(4, 2, 5, 5));
        panel.setBorder(BorderFactory.createTitledBorder("成绩信息"));
        
        // 创建学生下拉框
        studentComboBox = new JComboBox<>();
        updateStudentComboBox();
        
        // 创建表单字段
        chineseField = new JTextField(20);
        mathField = new JTextField(20);
        englishField = new JTextField(20);
        
        // 添加组件到面板
        panel.add(new JLabel("学生:"));
        panel.add(studentComboBox);
        panel.add(new JLabel("语文成绩:"));
        panel.add(chineseField);
        panel.add(new JLabel("数学成绩:"));
        panel.add(mathField);
        panel.add(new JLabel("英语成绩:"));
        panel.add(englishField);
        
        return panel;
    }
    
    /**
     * 创建按钮面板
     */
    private JPanel createButtonPanel() {
        JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));
        
        // 创建按钮
        addButton = ThemeManager.createSuccessButton("添加");
        updateButton = ThemeManager.createButton("修改");
        deleteButton = ThemeManager.createDangerButton("删除");
        clearButton = ThemeManager.createButton("清空");
        
        // 添加按钮事件
        addButton.addActionListener(e -> addScore());
        updateButton.addActionListener(e -> updateScore());
        deleteButton.addActionListener(e -> deleteScore());
        clearButton.addActionListener(e -> clearForm());
        
        // 添加按钮到面板
        panel.add(addButton);
        panel.add(updateButton);
        panel.add(deleteButton);
        panel.add(clearButton);
        
        return panel;
    }
    
    /**
     * 更新学生下拉框
     */
    private void updateStudentComboBox() {
        studentComboBox.removeAllItems();
        for (String id : studentManager.getStudentMap().keySet()) {
            studentComboBox.addItem(id);
        }
    }
    
    /**
     * 添加成绩
     */
    private void addScore() {
        // 获取表单数据
        String studentId = (String) studentComboBox.getSelectedItem();
        String chineseText = chineseField.getText().trim();
        String mathText = mathField.getText().trim();
        String englishText = englishField.getText().trim();
        
        // 验证数据
        if (studentId == null || chineseText.isEmpty() || mathText.isEmpty() || englishText.isEmpty()) {
            JOptionPane.showMessageDialog(this, "请填写所有字段！", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }
        
        try {
            double chinese = Double.parseDouble(chineseText);
            double math = Double.parseDouble(mathText);
            double english = Double.parseDouble(englishText);
            
            // 验证成绩范围
            if (chinese < 0 || chinese > 100 || math < 0 || math > 100 || english < 0 || english > 100) {
                JOptionPane.showMessageDialog(this, "成绩必须在0-100之间！", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            
            // 创建成绩对象
            Score score = new Score(studentId, chinese, math, english);
            
            // 添加成绩
            boolean success = scoreManager.addScore(score);
            
            if (success) {
                // 刷新表格
                refreshData();
                
                // 清空表单
                clearForm();
                
                JOptionPane.showMessageDialog(this, "成绩添加成功！", "成功", JOptionPane.INFORMATION_MESSAGE);
            }
            
        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(this, "成绩必须是数字！", "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
    
    /**
     * 更新成绩
     */
    private void updateScore() {
        // 获取表单数据
        String studentId = (String) studentComboBox.getSelectedItem();
        String chineseText = chineseField.getText().trim();
        String mathText = mathField.getText().trim();
        String englishText = englishField.getText().trim();
        
        // 验证数据
        if (studentId == null || chineseText.isEmpty() || mathText.isEmpty() || englishText.isEmpty()) {
            JOptionPane.showMessageDialog(this, "请填写所有字段！", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }
        
        try {
            double chinese = Double.parseDouble(chineseText);
            double math = Double.parseDouble(mathText);
            double english = Double.parseDouble(englishText);
            
            // 验证成绩范围
            if (chinese < 0 || chinese > 100 || math < 0 || math > 100 || english < 0 || english > 100) {
                JOptionPane.showMessageDialog(this, "成绩必须在0-100之间！", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            
            // 创建成绩对象
            Score score = new Score(studentId, chinese, math, english);
            
            // 更新成绩
            boolean success = scoreManager.updateScore(score);
            
            if (success) {
                // 刷新表格
                refreshData();
                
                // 清空表单
                clearForm();
                
                JOptionPane.showMessageDialog(this, "成绩更新成功！", "成功", JOptionPane.INFORMATION_MESSAGE);
            }
            
        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(this, "成绩必须是数字！", "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
    
    /**
     * 删除成绩
     */
    private void deleteScore() {
        int selectedRow = scoreTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请先选择要删除的成绩记录！", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }
        
        String id = (String) tableModel.getValueAt(selectedRow, 0);
        
        int option = JOptionPane.showConfirmDialog(
                this,
                "确定要删除学号为 " + id + " 的成绩记录吗？",
                "删除确认",
                JOptionPane.YES_NO_OPTION);
        
        if (option == JOptionPane.YES_OPTION) {
            scoreManager.deleteScore(id);
            refreshData();
            clearForm();
        }
    }
    
    /**
     * 清空表单
     */
    private void clearForm() {
        if (studentComboBox.getItemCount() > 0) {
            studentComboBox.setSelectedIndex(0);
        }
        chineseField.setText("");
        mathField.setText("");
        englishField.setText("");
        scoreTable.clearSelection();
    }
    
    /**
     * 刷新表格数据
     */
    public void refreshData() {
        // 更新学生下拉框
        updateStudentComboBox();
        
        // 清空表格
        tableModel.setRowCount(0);
        
        // 添加数据到表格
        Map<String, Score> scores = scoreManager.getScores();
        Map<String, Student> students = studentManager.getStudentMap();
        
        for (Score score : scores.values()) {
            String studentId = score.getStudentId();
            String studentName = students.containsKey(studentId) ? students.get(studentId).getName() : "未知";
            
            Object[] rowData = {
                    studentId,
                    studentName,
                    score.getChinese(),
                    score.getMath(),
                    score.getEnglish(),
                    score.getTotalScore()
            };
            tableModel.addRow(rowData);
        }
    }
    
    /**
     * 搜索成绩
     */
    private void searchScores() {
        String keyword = searchField.getText().trim();
        if (keyword.isEmpty()) {
            refreshData(); // 如果搜索关键字为空，显示所有成绩
            return;
        }
        
        // 清空表格
        tableModel.setRowCount(0);
        
        // 获取学生和成绩数据
        Map<String, Student> students = studentManager.getStudentMap();
        Map<String, Score> scores = scoreManager.getScores();
        
        // 搜索匹配的成绩
        for (Score score : scores.values()) {
            String studentId = score.getStudentId();
            String studentName = students.containsKey(studentId) ? students.get(studentId).getName() : "未知";
            
            if (studentId.contains(keyword) || studentName.contains(keyword)) {
                Object[] rowData = {
                        studentId,
                        studentName,
                        score.getChinese(),
                        score.getMath(),
                        score.getEnglish(),
                        score.getTotalScore()
                };
                tableModel.addRow(rowData);
            }
        }
    }
    
    /**
     * 导出成绩数据
     */
    private void exportScores() {
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setDialogTitle("导出成绩数据");
        fileChooser.setSelectedFile(new java.io.File("scores_export.csv"));
        
        int userSelection = fileChooser.showSaveDialog(this);
        
        if (userSelection == JFileChooser.APPROVE_OPTION) {
            java.io.File fileToSave = fileChooser.getSelectedFile();
            try (java.io.PrintWriter writer = new java.io.PrintWriter(fileToSave)) {
                // 写入表头
                writer.println("学号,姓名,语文成绩,数学成绩,英语成绩,总成绩");
                
                // 获取学生和成绩数据
                Map<String, Student> students = studentManager.getStudentMap();
                Map<String, Score> scores = scoreManager.getScores();
                
                // 写入数据
                for (Score score : scores.values()) {
                    String studentId = score.getStudentId();
                    String studentName = students.containsKey(studentId) ? students.get(studentId).getName() : "未知";
                    
                    writer.printf("%s,%s,%.1f,%.1f,%.1f,%.1f%n",
                            studentId,
                            studentName,
                            score.getChinese(),
                            score.getMath(),
                            score.getEnglish(),
                            score.getTotalScore());
                }
                
                JOptionPane.showMessageDialog(this, "成绩数据导出成功！", "成功", JOptionPane.INFORMATION_MESSAGE);
            } catch (Exception e) {
                JOptionPane.showMessageDialog(this, "导出失败：" + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }
}